﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows8Accelerator.Core.Xaml.Model;

namespace Windows8Accelerator.Core.Xaml.Storage
{
    public class StringLoader : ModelBase
    {
        private string _Content;
        public string Content
        {
            get 
            {
                LoadContentAsync();
                return this._Content;
            }
            set { this.SetProperty(ref this._Content, value); }
        }

        private StorageLocation _StorageLocation;
        public StorageLocation StorageLocation
        {
            get { return this._StorageLocation; }
            set { this.SetProperty(ref this._StorageLocation, value); }
        }

        private bool _Loaded = false;

        public static async Task<string> GetContentAsync(string sourceFilePath, StorageLocation storageLocation)
        {
            if (!string.IsNullOrEmpty(sourceFilePath))
            {
                try
                {
                    using (var stream = await StorageHelperBase.Instance.OpenFileReadAsync(sourceFilePath, storageLocation))
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
                catch { }
            }
            return null;
        }

        public async Task LoadContentAsync()
        {
            if (_Loaded)
                return;

            if (!string.IsNullOrEmpty(SourceFilePath))
            {
                try
                {
                    Content = await GetContentAsync(SourceFilePath, StorageLocation);
                    _Loaded = true;
                }
                catch { }
            }
        }

        private string _SourceUrl;
        public string SourceUrl
        {
            get { return this._SourceUrl; }
            set { this.SetProperty(ref this._SourceUrl, value); }
        }

        private string _SourceFilePath;
        public string SourceFilePath
        {
            get { return this._SourceFilePath; }
            set { this.SetProperty(ref this._SourceFilePath, value); }
        }

    }
}
